package org.fing.edu.uy.esbadp.admServices.mbean;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;

import org.fing.edu.uy.esbadp.core.constants.EsbAdpServiceMetadataKeys;
import org.fing.edu.uy.esbadp.core.entity.DMRegisteredService;
import org.fing.edu.uy.esbadp.core.entity.KeyValuePair;
import org.fing.edu.uy.esbadp.core.entity.MetaDataConfig;
import org.fing.edu.uy.esbadp.init.AdpConfigurationLoader;
import org.fing.edu.uy.esbadp.logger.LoggerADP;
import org.fing.edu.uy.esbadp.modules.persistance.ServiceManagerFactory;
import org.fing.edu.uy.esbadp.modules.persistance.ServiceManagerInterface;
import org.fing.edu.uy.esbadp.utils.FileUtils;


public class EsbAdmServices implements EsbAdmServicesMBean {
	
	private static java.util.logging.Logger logger = LoggerADP.getLogger(EsbAdmServices.class.getSimpleName());
	
	@Override
	public List<DMRegisteredService> getEquivalentsServices(Long serviceId) throws SQLException {
		try{
			ServiceManagerInterface serviceManager = ServiceManagerFactory.getServiceManager();
			return serviceManager.getAllEquivVirtualServices(serviceId);
		}catch (Exception ex) {
			logger.log(Level.SEVERE, "Exception in EsbAdmServices when invoke getEquivalentsServices().", ex);
			return null;
		}
	}

	@Override
	public List<DMRegisteredService> getAllVirtualServices() throws SQLException {		
		return ServiceManagerFactory.getServiceManager().getAllVirtualServices();				
	}

	@Override
	public int persistVirtualService(DMRegisteredService virtualService)throws SQLException {
		return ServiceManagerFactory.getServiceManager().persistVirtualService(virtualService);
	}

	@Override
	public void persistVirtualServiceMetadata(MetaDataConfig meta, Long serviceID) throws SQLException {
		ServiceManagerFactory.getServiceManager().persistVirtualServiceMetadata(meta,serviceID);		
	}

	@Override
	public void persistEquivVirtualServices(List<DMRegisteredService> equiv, Long serviceID) throws SQLException {
		ServiceManagerFactory.getServiceManager().persistEquivVirtualServices(equiv,serviceID);		
	}

	@Override
	public List<DMRegisteredService> getAllEquivVirtualServices(Long serviceID)	throws SQLException {
		return ServiceManagerFactory.getServiceManager().getAllEquivVirtualServices(serviceID);		
	}

	@Override
	public DMRegisteredService getVirtualService(String endpointUrl)throws SQLException {
		return ServiceManagerFactory.getServiceManager().getVirtualService(endpointUrl);		
	}

	@Override
	public DMRegisteredService getVirtualService(Long serviceID)throws SQLException {
		return ServiceManagerFactory.getServiceManager().getVirtualService(serviceID);		
	}

	@Override
	public MetaDataConfig getVirtualServiceMetadata(Long serviceID)	throws SQLException {
		return ServiceManagerFactory.getServiceManager().getVirtualServiceMetadata(serviceID);		
	}

	@Override
	public int deleteVirtualServiceMetadata(String metaKey, Long serviceID)	throws SQLException {
		return ServiceManagerFactory.getServiceManager().deleteVirtualServiceMetadata(metaKey,serviceID);
	}

	@Override
	public int deleteVirtualService(Long serviceID) throws SQLException {
		return ServiceManagerFactory.getServiceManager().deleteVirtualService(serviceID);	
	}

	@Override
	public int updateService(DMRegisteredService virtualService)throws SQLException {
		return ServiceManagerFactory.getServiceManager().updateService(virtualService);	
	}

	@Override
	public int updateMetadata(KeyValuePair meta, Long serviceID) throws SQLException {
		return ServiceManagerFactory.getServiceManager().updateMetadata(meta,serviceID);	
	}

	@Override
	public int deleteEquivRelation(Long serviceID) throws SQLException {
		return ServiceManagerFactory.getServiceManager().deleteEquivRelation(serviceID);		
	}
	
	@Override
	public void saveToCanonicalXSL(String xsl , Long serviceID){		
		
		try {
			ServiceManagerFactory.getServiceManager().saveToCanonicalXSL(xsl, serviceID);
		} catch (IOException e) {
			logger.log(Level.SEVERE, "Exception in EsbAdmServices when saving To Canonical XSL", e);				
		}
	}
	
	@Override
	public void saveFromCanonicalXSL(String xsl , Long serviceID){
		try {
			ServiceManagerFactory.getServiceManager().saveFromCanonicalXSL(xsl, serviceID);
		} catch (IOException e) {
			logger.log(Level.SEVERE, "Exception in EsbAdmServices when saving From Canonical XSL", e);			
		}	
	}
	
	@Override
	public String getToCanonicalXSL(Long serviceID){
		String ret = "";
		try {
			ret =  ServiceManagerFactory.getServiceManager().getToCanonicalXSL(serviceID);
		} catch (IOException e) {
			logger.log(Level.SEVERE, "Exception in EsbAdmServices when reading To Canonical XSL", e);			
		}		
		return ret;
	}
	
	@Override
	public String getFromCanonicalXSL(Long serviceID){
		String ret = "";
		try {
			ret =  ServiceManagerFactory.getServiceManager().getFromCanonicalXSL(serviceID);
		} catch (IOException e) {
			logger.log(Level.SEVERE, "Exception in EsbAdmServices when reading From Canonical XSL", e);			
		}		
		return ret;
	}
	
	@Override
	public void reloadAdpActions() {
		AdpConfigurationLoader adpConf = new AdpConfigurationLoader();
		adpConf.registerAdpAction();	
	}
	
	@Override
	public void reloadAdpServiceRequirements(){
		AdpConfigurationLoader adpConf = new AdpConfigurationLoader();
		adpConf.registerAdpServiceRequirements();
	}
	
	@Override
	public void reloadAdpMonitorMechanism() {
		AdpConfigurationLoader adpConf = new AdpConfigurationLoader();
		adpConf.registerAdpMonitorMechanism();	
	}
	
	@Override
	public void preloadStubEGovServices(String hostName) throws SQLException {
		//Agrega los servicios de eGov
		DMRegisteredService srv1 = new DMRegisteredService();
		srv1.setServiceID(1);
		srv1.setEsbProyectName("SRV-2.esb");
		srv1.setEndPointURL("http://" + hostName + ":54330/BPSWS");
		srv1.setVirtualServiceCategory("eGov");
		srv1.setVirtualServiceName("BPSWSProxy");
		srv1.addMetadata(EsbAdpServiceMetadataKeys.dataService, "true");
		srv1.addMetadata(EsbAdpServiceMetadataKeys.invocationsQuantityPerUnitTimeLimit, "10");
		srv1.addMetadata(EsbAdpServiceMetadataKeys.responseTimeLimit, "10");
		srv1.addMetadata(EsbAdpServiceMetadataKeys.successInvocationRateLimit, "10");
		srv1.addMetadata(EsbAdpServiceMetadataKeys.newNumericValue, "0");
		srv1.addMetadata(EsbAdpServiceMetadataKeys.newStringValue, "defaultValue");
		srv1.addMetadata(EsbAdpServiceMetadataKeys.dataDelayTime, "100");

		DMRegisteredService srv2 = new DMRegisteredService();
		srv2.setServiceID(2);
		srv2.setEsbProyectName("SRV-2.esb");
		srv2.setEndPointURL("http://" + hostName + ":54331/DGIWS");
		srv2.setVirtualServiceCategory("eGov");
		srv2.setVirtualServiceName("DGIWSProxy");
		srv2.addMetadata(EsbAdpServiceMetadataKeys.dataService, "true");
		srv2.addMetadata(EsbAdpServiceMetadataKeys.invocationsQuantityPerUnitTimeLimit, "100");
		srv2.addMetadata(EsbAdpServiceMetadataKeys.responseTimeLimit, "100");
		srv2.addMetadata(EsbAdpServiceMetadataKeys.successInvocationRateLimit, "100");
		srv2.addMetadata(EsbAdpServiceMetadataKeys.newNumericValue, "0");
		srv2.addMetadata(EsbAdpServiceMetadataKeys.newStringValue, "defaultValue");
		srv2.addMetadata(EsbAdpServiceMetadataKeys.dataDelayTime, "120");

		DMRegisteredService srv3 = new DMRegisteredService();
		srv3.setServiceID(3);
		srv3.setEsbProyectName("SRV-2.esb");
		srv3.setEndPointURL("http://" + hostName + ":54332/DNICWS");
		srv3.setVirtualServiceCategory("eGov");
		srv3.setVirtualServiceName("DNICWSProxy");
		srv3.addMetadata(EsbAdpServiceMetadataKeys.dataService, "true");
		srv3.addMetadata(EsbAdpServiceMetadataKeys.invocationsQuantityPerUnitTimeLimit, "1000");
		srv3.addMetadata(EsbAdpServiceMetadataKeys.responseTimeLimit, "1000");
		srv3.addMetadata(EsbAdpServiceMetadataKeys.successInvocationRateLimit, "100");
		srv3.addMetadata(EsbAdpServiceMetadataKeys.newNumericValue, "0");
		srv3.addMetadata(EsbAdpServiceMetadataKeys.newStringValue, "defaultValue");
		srv3.addMetadata(EsbAdpServiceMetadataKeys.dataDelayTime, "150");
		
		try {
			// voy a eliminar los servicios existentes ( si existian )
			ServiceManagerInterface mgr = ServiceManagerFactory.getServiceManager();				
			List<DMRegisteredService> serviciosViejos = mgr.getAllVirtualServices();
			for (DMRegisteredService aux : serviciosViejos) {
				if(aux.getEsbProyectName().equalsIgnoreCase("SRV-2.esb")){				
					mgr.deleteEquivRelation(aux.getServiceID());
				}
			}
			
			for (DMRegisteredService aux : serviciosViejos) {
				if(aux.getEsbProyectName().equalsIgnoreCase("SRV-2.esb")){
					logger.info("Remove service " + aux.getServiceID());
					mgr.deleteVirtualService(aux.getServiceID());
				}
			}
			
			// voy a cargar los nuevos servicios
			long idSrv = mgr.persistVirtualService(srv1);
			logger.info("Register new service with id " + idSrv);
			mgr.saveFromCanonicalXSL(FileUtils.readFileToString("META-INF/canonicEgov/BPS_fromCanonic.xsl"), idSrv);
			mgr.saveToCanonicalXSL(FileUtils.readFileToString("META-INF/canonicEgov/BPS_toCanonic.xsl"), idSrv);
			
			idSrv = mgr.persistVirtualService(srv2);
			logger.info("Register new service with id " + idSrv);
			mgr.saveFromCanonicalXSL(FileUtils.readFileToString("META-INF/canonicEgov/DGI_fromCanonic.xsl"), idSrv);
			mgr.saveToCanonicalXSL(FileUtils.readFileToString("META-INF/canonicEgov/DGI_toCanonic.xsl"), idSrv);
			
			idSrv = mgr.persistVirtualService(srv3);
			logger.info("Register new service with id " + idSrv);
			mgr.saveFromCanonicalXSL(FileUtils.readFileToString("META-INF/canonicEgov/DNIC_fromCanonic.xsl"), idSrv);
			mgr.saveToCanonicalXSL(FileUtils.readFileToString("META-INF/canonicEgov/DNIC_toCanonic.xsl"), idSrv);
			
		} catch (Exception ex) {
			logger.log(Level.SEVERE, "Error loading stub service ->", ex);
		}
	}
	
}
